/** Description of WidgetUpdateTask.java 
 *
 * @author panther
 * Jayant Pratim Saikia
 * jay.saikia@gmail.com
 *
 */
package com.panther.awp.android.smoker.async;

import java.util.HashMap;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;

import com.panther.awp.android.smoker.cache.Cache;
import com.panther.awp.android.smoker.database.AbstractDbAdapter;
import com.panther.awp.android.smoker.database.MyDBWrapper;
import com.panther.awp.android.smoker.helpers.GeneralHelper;

public class WidgetUpdateTask extends AsyncTask<Void, Void, HashMap<String, Object>> {
	
	private Context context;
	
	public WidgetUpdateTask(Context context) {
		this.context = context;
	}

	@Override
	protected HashMap<String, Object> doInBackground(Void... params) {
		HashMap<String, Object> hMapResult = new HashMap<String, Object>();
		//Get most recently smoked brand and update view
		Cursor cursor = MyDBWrapper.getInstance(context).getmTTDbHelper().fetchLatestSmokeEntry(); //Returns one row
		cursor.moveToFirst();
		if(!cursor.isAfterLast()) {
			Long brandId = cursor.getLong(cursor.getColumnIndexOrThrow(AbstractDbAdapter.TT_BRAND_ID));
			Cursor brandsCursor = MyDBWrapper.getInstance(context).getmBTDbHelper().fetch(brandId);
			brandsCursor.moveToFirst();
			if(!brandsCursor.isAfterLast()) {
				hMapResult.put("returnIdStr", brandsCursor.getString(brandsCursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_PK_ID)));
				hMapResult.put("returnBrand", brandsCursor.getString(brandsCursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND)));
				hMapResult.put("returnBrandPrice", brandsCursor.getString(brandsCursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND_PRICE)));
				String brandUri = brandsCursor.getString(brandsCursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_IMAGE_URI));
				hMapResult.put("bitmapImage", Cache.getCacheFile(brandUri));
			} else {
				hMapResult.put("returnIdStr", "");
				hMapResult.put("returnBrand", "Last Smoked Brand Not Found");
				hMapResult.put("returnBrandPrice", "");
				hMapResult.put("bitmapImage", null);
			}
			brandsCursor.close();
		} else {
			hMapResult.put("returnIdStr", "");
			hMapResult.put("returnBrand", "No Brands Smoked");
			hMapResult.put("returnBrandPrice", "");
			hMapResult.put("bitmapImage", null);
		}
		cursor.close();
		return hMapResult;
	}
	
	@Override
	protected void onPostExecute(HashMap<String, Object> resultMap) {
		super.onPostExecute(resultMap);
		if(resultMap.get("bitmapImage") == null) {
			GeneralHelper.updateRemoteView(context, (String) resultMap.get("returnIdStr"), (String) resultMap.get("returnBrand"), (String) resultMap.get("returnBrandPrice"), null);
		} else {
			GeneralHelper.updateRemoteView(context, (String) resultMap.get("returnIdStr"), (String) resultMap.get("returnBrand"), (String) resultMap.get("returnBrandPrice"), (Bitmap)resultMap.get("bitmapImage"));
		}
	}
}
